import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import * as chatService from '../services/chat';
import type { ChatMessage, ChatHistory } from '../types/chat';

export const useChatStore = defineStore('chat', () => {
  // 状态
  const currentChatId = ref<string>('');
  const messages = ref<ChatMessage[]>([]);
  const historyChats = ref<ChatHistory[]>([]);
  const loading = ref(false);
  const currentModel = ref('openai');

  // 计算属性
  const hasMessages = computed(() => messages.value.length > 0);
  const latestMessage = computed(() => messages.value[messages.value.length - 1]);

  // 创建新对话
  async function createNewChat() {
    currentChatId.value = '';
    messages.value = [];
  }

  // 保存当前对话
  async function saveCurrentChat() {
    if (!hasMessages.value) return;
    
    try {
      const response = await chatService.getChatHistory();
      historyChats.value = response.data;
    } catch (error) {
      console.error('Failed to save chat:', error);
      throw error;
    }
  }

  // 加载历史对话
  async function loadHistoryChats() {
    try {
      const response = await chatService.getChatHistory();
      historyChats.value = response.data;
    } catch (error) {
      console.error('Failed to load history:', error);
      throw error;
    }
  }

  // 加载特定对话
  async function loadChat(chatId: string) {
    try {
      const response = await chatService.getChatDetail(chatId);
      currentChatId.value = chatId;
      messages.value = response.data.messages;
    } catch (error) {
      console.error('Failed to load chat:', error);
      throw error;
    }
  }

  // 发送消息
  async function sendMessage(content: string) {
    if (!content.trim()) return;

    try {
      loading.value = true;
      
      // 添加用户消息
      const userMessage: ChatMessage = {
        role: 'user',
        content,
        timestamp: new Date().toISOString()
      };
      messages.value.push(userMessage);

      // 发送到服务器
      const response = await chatService.sendChatMessage({
        question: content,
        model: currentModel.value
      });

      // 添加AI回复
      const assistantMessage: ChatMessage = {
        role: 'assistant',
        content: response.data,
        timestamp: new Date().toISOString()
      };
      messages.value.push(assistantMessage);

      // 如果是新对话，保存到历史记录
      if (!currentChatId.value) {
        await saveCurrentChat();
      }
    } catch (error) {
      console.error('Failed to send message:', error);
      throw error;
    } finally {
      loading.value = false;
    }
  }

  // 切换模型
  function switchModel(model: string) {
    currentModel.value = model;
  }

  // 删除对话
  async function deleteChat(chatId: string) {
    try {
      await chatService.deleteChatHistory(chatId);
      historyChats.value = historyChats.value.filter(chat => chat.id !== chatId);
      
      if (currentChatId.value === chatId) {
        createNewChat();
      }
    } catch (error) {
      console.error('Failed to delete chat:', error);
      throw error;
    }
  }

  // 清空所有历史
  async function clearAllHistory() {
    try {
      await chatService.clearAllHistory();
      historyChats.value = [];
      createNewChat();
    } catch (error) {
      console.error('Failed to clear history:', error);
      throw error;
    }
  }

  return {
    currentChatId,
    messages,
    historyChats,
    loading,
    currentModel,
    hasMessages,
    latestMessage,
    createNewChat,
    loadHistoryChats,
    loadChat,
    sendMessage,
    switchModel,
    deleteChat,
    clearAllHistory
  };
}); 